package org.csu.jpetstore_front.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.jpetstore_front.common.CommonResponse;
import org.csu.jpetstore_front.entity.Item;
import org.csu.jpetstore_front.entity.Product;
import org.csu.jpetstore_front.persistence.ItemMapper;
import org.csu.jpetstore_front.persistence.ProductMapper;
import org.csu.jpetstore_front.service.ItemService;
import org.csu.jpetstore_front.vo.SearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("itemService")
public class ItemServiceImpl implements ItemService {


    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public CommonResponse<List<SearchVO>> searchByKeyword(String keyword) {


        List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().like("name", keyword));

        List<SearchVO> items = new ArrayList<SearchVO>();

        productList.forEach(product -> {

            List<Item> itemList = itemMapper.selectList(new QueryWrapper<Item>().eq("productid", product.getProductId()));

            itemList.forEach(item -> {
                SearchVO searchVO = new SearchVO();
                searchVO.setName(product.getName());
                searchVO.setImgURL(product.getDescription());
                searchVO.setId(item.getItemId());
                searchVO.setPrice(item.getListPrice());
                items.add(searchVO);
            });
        });
        return CommonResponse.createForSuccess(items);
    }

}
